"""
剪映专业版集成模块
处理视频格式转换和草稿文件导入
"""

import json
import logging
import os
import shutil
import uuid
from datetime import datetime
from pathlib import Path
from typing import Dict, List, Optional

import yaml


class JianYingIntegration:
    """剪映专业版集成类"""
    
    def __init__(self, config_path: str = "config.yaml"):
        """
        初始化剪映集成
        
        Args:
            config_path: 配置文件路径
        """
        self.config = self._load_config(config_path)
        self.logger = logging.getLogger(__name__)
        
    def _load_config(self, config_path: str) -> Dict:
        """加载配置文件"""
        with open(config_path, 'r', encoding='utf-8') as f:
            return yaml.safe_load(f)
    
    def import_to_jianying(self, video_path: str, project_name: Optional[str] = None) -> str:
        """
        将视频导入到剪映专业版草稿
        
        Args:
            video_path: 视频文件路径
            project_name: 项目名称
            
        Returns:
            创建的草稿项目路径
        """
        self.logger.info(f"开始导入视频到剪映: {video_path}")
        
        # 检查视频文件
        if not os.path.exists(video_path):
            raise FileNotFoundError(f"视频文件不存在: {video_path}")
        
        # 转换视频格式（如果需要）
        converted_path = self._convert_video_format(video_path)
        
        # 创建剪映草稿项目
        draft_path = self._create_jianying_draft(converted_path, project_name)
        
        self.logger.info(f"视频成功导入剪映草稿: {draft_path}")
        return draft_path
    
    def _convert_video_format(self, video_path: str) -> str:
        """
        转换视频格式为剪映兼容格式
        
        Args:
            video_path: 原始视频路径
            
        Returns:
            转换后的视频路径
        """
        # 检查是否需要转换
        if self._is_jianying_compatible(video_path):
            self.logger.info("视频格式兼容，无需转换")
            return video_path
        
        # 创建临时目录
        temp_dir = Path(self.config['paths']['temp_dir'])
        temp_dir.mkdir(exist_ok=True)
        
        # 转换视频格式（这里需要安装ffmpeg）
        output_path = temp_dir / f"converted_{Path(video_path).stem}.mp4"
        
        try:
            # 使用ffmpeg进行格式转换
            import subprocess
            
            cmd = [
                'ffmpeg', '-i', video_path,
                '-c:v', 'libx264',
                '-c:a', 'aac',
                '-movflags', '+faststart',
                '-y', str(output_path)
            ]
            
            result = subprocess.run(cmd, capture_output=True, text=True)
            if result.returncode != 0:
                raise Exception(f"视频转换失败: {result.stderr}")
            
            self.logger.info(f"视频格式转换完成: {output_path}")
            return str(output_path)
            
        except Exception as e:
            self.logger.error(f"视频转换失败: {e}")
            # 如果转换失败，尝试直接复制（可能格式已经兼容）
            shutil.copy2(video_path, output_path)
            self.logger.warning("使用原始视频文件（转换失败）")
            return str(output_path)
    
    def _is_jianying_compatible(self, video_path: str) -> bool:
        """检查视频格式是否兼容剪映"""
        compatible_extensions = {'.mp4', '.mov', '.avi', '.mkv', '.wmv'}
        return Path(video_path).suffix.lower() in compatible_extensions
    
    def _create_jianying_draft(self, video_path: str, project_name: Optional[str] = None) -> str:
        """
        创建剪映草稿项目
        
        Args:
            video_path: 视频文件路径
            project_name: 项目名称
            
        Returns:
            草稿项目路径
        """
        jianying_config = self.config['jianying']
        
        # 展开环境变量路径
        drafts_path = os.path.expandvars(jianying_config['drafts_path'])
        
        # 创建项目名称
        if not project_name:
            project_name = jianying_config['project']['name']
        
        # 生成唯一项目ID
        project_id = str(uuid.uuid4())
        draft_folder = Path(drafts_path) / project_id
        draft_folder.mkdir(parents=True, exist_ok=True)
        
        # 创建草稿配置文件
        self._create_draft_config(draft_folder, project_name, video_path)
        
        # 复制视频文件到草稿目录
        media_folder = draft_folder / "Media"
        media_folder.mkdir(exist_ok=True)
        
        video_filename = f"video_{int(datetime.now().timestamp())}{Path(video_path).suffix}"
        target_video_path = media_folder / video_filename
        shutil.copy2(video_path, target_video_path)
        
        return str(draft_folder)
    
    def _create_draft_config(self, draft_folder: Path, project_name: str, video_path: str):
        """创建草稿配置文件"""
        jianying_config = self.config['jianying']
        
        # 草稿配置文件结构
        draft_config = {
            "draftInfo": {
                "draftId": draft_folder.name,
                "draftName": project_name,
                "createTime": int(datetime.now().timestamp() * 1000),
                "modifyTime": int(datetime.now().timestamp() * 1000),
                "resolution": jianying_config['project']['resolution'],
                "fps": jianying_config['project']['fps']
            },
            "mediaInfo": {
                "mediaList": [
                    {
                        "id": str(uuid.uuid4()),
                        "type": "video",
                        "path": f"Media/{Path(video_path).name}",
                        "duration": 0,  # 实际使用时需要获取视频时长
                        "width": 1920,
                        "height": 1080
                    }
                ]
            },
            "timelineInfo": {
                "tracks": [
                    {
                        "type": "video",
                        "segments": [
                            {
                                "id": str(uuid.uuid4()),
                                "mediaId": "",  # 需要与mediaList中的id对应
                                "start": 0,
                                "duration": 0  # 需要与视频时长对应
                            }
                        ]
                    }
                ]
            }
        }
        
        # 保存配置文件
        config_file = draft_folder / "draft_content.json"
        with open(config_file, 'w', encoding='utf-8') as f:
            json.dump(draft_config, f, ensure_ascii=False, indent=2)
    
    def list_drafts(self) -> List[Dict]:
        """列出所有剪映草稿项目"""
        jianying_config = self.config['jianying']
        drafts_path = os.path.expandvars(jianying_config['drafts_path'])
        
        if not os.path.exists(drafts_path):
            return []
        
        drafts = []
        for draft_folder in Path(drafts_path).iterdir():
            if draft_folder.is_dir():
                config_file = draft_folder / "draft_content.json"
                if config_file.exists():
                    try:
                        with open(config_file, 'r', encoding='utf-8') as f:
                            config = json.load(f)
                            drafts.append({
                                'id': draft_folder.name,
                                'name': config.get('draftInfo', {}).get('draftName', 'Unknown'),
                                'path': str(draft_folder),
                                'create_time': config.get('draftInfo', {}).get('createTime', 0)
                            })
                    except Exception as e:
                        self.logger.warning(f"读取草稿配置失败 {draft_folder}: {e}")
        
        return drafts